package com.cn.wanxi.interceptor;

import com.cn.wanxi.common.RedisNumTool;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 */
public class MyInterceptor implements HandlerInterceptor {
    /*目标方法执行前执行*/
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        // 设置：Access-Control-Allow-Origin头，处理跨域问题
        resp.setHeader("Access-Control-A1low-Methods", "POST,GEI，OPTIONS，DELETE");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        resp.setHeader("Access-Control-A1low-Origin", req.getHeader("Origin"));

        req.setCharacterEncoding("UTF-8");
        /*会导致浏览器控制台乱码*/
//        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf-8");

        String path = req.getServletPath();
        Boolean bool = path.startsWith("/back")
                && !path.endsWith("/get")
                && !path.endsWith("/find")
                && !path.endsWith("/id")
                && !path.endsWith("/count")
                && !path.endsWith("/previous")
                && !path.endsWith("/next")
                && !path.endsWith("/login")
                && !path.endsWith("/code");
        if (bool) {
            boolean login = false;
            Jedis jedis = new Jedis();
            jedis.select(RedisNumTool.REDIS_LOGIN_SESSION);
            String loginUsername = jedis.get("loginUsername");
            login = loginUsername != null;
            if (!login) {
                resp.sendRedirect("/x-login.html");
                return false;
            }
            return true;
        } else {
            return true;
        }
    }

    /*目标方法执行之后，视图对象返回之前执行*/
    @Override
    public void postHandle(HttpServletRequest req, HttpServletResponse resp, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /*在流程之后执行*/
    @Override
    public void afterCompletion(HttpServletRequest req, HttpServletResponse resp, Object handler, Exception ex) throws Exception {

    }
}
